package com.itheima.service.store.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.store.SyslogDao;
import com.itheima.domain.store.Syslog;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.SyslogService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class SyslogServiceImpl  implements SyslogService {

    @Override
    public void save(Syslog syslog) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);
            String id = UUID.randomUUID().toString();
            syslog.setId(id);

            //syslog.setCreateTime(new Date());
            mapper.save(syslog);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delete(String id) {

        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);


            mapper.delete(id);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void update(Syslog syslog) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);


            mapper.update(syslog);
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Syslog> findAll() {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);


            List<Syslog> list = mapper.findAll();
            return  list;

        } catch (Exception e) {

            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Syslog findById(String id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);


            Syslog byId = mapper.findById(id);
            return  byId;

        } catch (Exception e) {

            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageInfo findAll(int page, int size) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);

            PageHelper.startPage(page,size);
            List<Syslog> list = mapper.findAll();
            for (Syslog syslog : list) {
                Date visitTime = syslog.getVisitTime();
                SimpleDateFormat sp =new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String format =sp.format(visitTime);
                syslog.setVisitTimeStr(format);
            }
            PageInfo info =new PageInfo(list);
            return  info;

        } catch (Exception e) {

            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void deleteSelected(String[] ids) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);



            if (ids != null) {
                for (String id : ids) {
                    System.out.println(id);
                    mapper.delete(id);
                    TransactionUtil.commit(sqlSession);
                }
            }


        } catch (Exception e) {

            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    @Override
    public void getReport() throws IOException {


        SqlSession sqlSession = null;
        List<Syslog> syslogList=null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            SyslogDao mapper = MapperFactory.getMapper(sqlSession, SyslogDao.class);
           syslogList=mapper.findAll();


        } catch (Exception e) {

            throw new RuntimeException(e);
        }finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //1.获取到对应的Excel文件，工作簿文件
        Workbook wb = new XSSFWorkbook();
        //2.创建工作表
        Sheet s = wb.createSheet("操作数据文件");

        //设置通用配置
//        s.setColumnWidth(4,100);
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);

        //制作标题
        s.addMergedRegion(new CellRangeAddress(1,1,1,7));

        Row row_1 = s.createRow(1);
        Cell cell_1_1 = row_1.createCell(1);
        cell_1_1.setCellValue("日志导出");
        //创建一个样式
        CellStyle cs_title = wb.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
        cell_1_1.setCellStyle(cs_title);

        //制作表头
        String[] fields = {"访问ID","访问时间","访问用户","访问IP","资源URl",
                "执行时间","访问方法"};
        Row row_2 = s.createRow(2);

        for (int i = 0; i < fields.length; i++) {
            Cell cell_2_temp = row_2.createCell(1 + i); //++
            cell_2_temp.setCellValue(fields[i]);    //++
            cell_2_temp.setCellStyle(cs_field);
        }

        //制作数据区





        int row_index = 0;
        for (Syslog q : syslogList) {
            int cell_index = 0;
            Row row_temp = s.createRow(3 + row_index++);

            Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
            cell_data_1.setCellValue(q.getId());    //++
            cell_data_1.setCellStyle(cs_field);



            Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
            cell_data_2.setCellValue(q.getVisitTime());    //++
            cell_data_2.setCellStyle(cs_field);

            Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
            cell_data_3.setCellValue(q.getUsername());    //++
            cell_data_3.setCellStyle(cs_field);

            Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
            cell_data_4.setCellValue(q.getIp());    //++
            cell_data_4.setCellStyle(cs_field);

            Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
            cell_data_5.setCellValue(q.getUrl());    //++
            cell_data_5.setCellStyle(cs_field);

            Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
            cell_data_6.setCellValue(q.getExecutionTime());    //++
            cell_data_6.setCellStyle(cs_field);

            Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
            cell_data_7.setCellValue(q.getMethod());    //++
            cell_data_7.setCellStyle(cs_field);


        }

        //创建一个文件对象，作为excel文件内容的输出文件
        File f = new File("test.xlsx");
        //输出时通过流的形式对外输出，包装对应的目标文件
        OutputStream os = new FileOutputStream(f);
        //将内存中的workbook数据写入到流中
        wb.write(os);
        wb.close();
        os.close();

    }

    @Override
    public PageInfo<Syslog> findByMethodName(int page , int size ,String methodName) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        SyslogDao sysLogDao =MapperFactory.getMapper(sqlSession, SyslogDao.class);
        PageHelper.startPage(page, size);
       List<Syslog> all = sysLogDao.findByMethod(methodName);
        PageInfo pageInfo = new PageInfo(all);
        return pageInfo;
    }
}
